package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
)

func main() {
	engine := gin.Default()

	engine.GET("/download", downloadHandler)
	engine.POST("/upload", uploadHandler)

	engine.Run("0.0.0.0:9000")
}

func uploadHandler(ctx *gin.Context) {
	// 获取上传的文件
	file, header, err := ctx.Request.FormFile("file")
	if err != nil {
		ctx.String(http.StatusBadRequest, fmt.Sprintf("上传文件失败: %s", err.Error()))
		return
	}
	defer file.Close()

	// 获取文件名
	filename := header.Filename

	// 创建目标文件
	out, err := os.Create("upload/" + filename)
	if err != nil {
		ctx.String(http.StatusInternalServerError, fmt.Sprintf("创建文件失败: %s", err.Error()))
		return
	}
	defer out.Close()

	// 将上传的文件内容写入目标文件
	_, err = io.Copy(out, file)
	if err != nil {
		ctx.String(http.StatusInternalServerError, fmt.Sprintf("写入文件失败: %s", err.Error()))
		return
	}
}

func downloadHandler(ctx *gin.Context) {
	filename := ctx.Query("filename")

	path := "upload/" + filename

	// 设置响应头
	ctx.Header("Content-Description", "File Transfer")
	ctx.Header("Content-Type", "application/octet-stream")
	ctx.Header("Content-Disposition", "attachment; filename=" + filename)
	ctx.Header("Content-Transfer-Encoding", "binary")
	ctx.Header("Expires", "0")
	ctx.Header("Cache-Control", "must-revalidate")
	ctx.Header("Pragma", "public")

	ctx.File(path)
}

